<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Pocket extends Model
{
    protected $fillable = [
        'customer_id',
        'password',
        'amount', // 余额: 单位: 分
    ];

    public static function getPocket($customerId): self
    {
        return static::firstOrCreate([
            'customer_id' => $customerId
        ], [
            'amount' => 0,
            'password' => '',
        ]);
    }

    // 充值
    public function recharge($amount, $comment = '系统赠送')
    {
        DB::beginTransaction();

        try {
            $this->increment('amount', $amount);

            PocketLog::log($this->customer_id, $amount, $comment);

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }

        return true;
    }

    // 消费
    public function consume($amount, $comment = '自动过期')
    {
        DB::beginTransaction();

        if ($this->amount < $amount) {
            return false;
        }

        try {
            $this->decrement('amount', $amount);
            PocketLog::log($this->customer_id, $amount, $comment, false);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }

        return true;
    }
}
